package com.newland.mesdk.demo.device;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager.BadTokenException;

import com.newland.mtype.DeviceMenuEvent;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtypex.bluetooth.BlueToothV100ConnParams;
import com.newland.mesdk.demo.activity.BaseActivity;
import com.newland.mesdk.demo.adapter.ListButtonClickListener;
import com.newland.mesdk.demo.adapter.OptionsDialog;
import com.newland.mesdk.demo.adapter.OptionsDialog.OnBondClickedListener;
import com.newland.mesdk.demo.adapter.OptionsDialog.OnOptionsClickedListener;
import com.newland.mesdk.demo.moduleinterface.DeviceControllerInterface;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF on 2015/8/14 0014. 蓝牙设备
 */
public class BlueToothDevice extends AbstractDevice {
	private static final String ME3X_DRIVER_NAME = "com.newland.me.ME3xDriver";
	private int REQUEST_ENABLE = 0;
	private OptionsDialog dialog;
	private String deviceToConnect, deviceName;
	private DeviceControllerInterface controller = null;
	private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	private List<BlueToothDeviceContext> discoveredDevices = new ArrayList<BlueToothDeviceContext>();
	private BaseActivity baseActivity;
	private BluetoothDevice bluedevice;
	private boolean isconnect = false;
	private List<BluetoothDevice> bonddevices = new ArrayList<BluetoothDevice>();

	private final BroadcastReceiver discoveryReciever = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {

				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (ifAddressExist(device.getAddress()) || ifBondExist(device.getAddress())) {
					return;
				}

				BlueToothDeviceContext tempDevice = new BlueToothDeviceContext(device.getName() == null ? device.getAddress() : device.getName(),
						device.getAddress());
				getDiscoveredDevices().add(tempDevice);
				dialog.refreshList(tempDevice);
			}

		}
	};

	private void unpairDevice(BluetoothDevice device) {
		try {
			Method m = device.getClass().getMethod("removeBond", (Class[]) null);
			m.invoke(device, (Object[]) null);
		} catch (Exception e) {
			Log.e("BlueToothDevice:", e.getMessage());
			baseActivity.showMessage("获取未配对设备异常："+e.getMessage(), MessageTag. ERROR);
		}
	}

	public BlueToothDevice(BaseActivity baseActivity) {
		super();
		/**
		 * 注册一个蓝牙发现监听器
		 */
		this.baseActivity = baseActivity;
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		baseActivity.registerReceiver(discoveryReciever, filter);
	}

	/**
	 * 检查是蓝牙地址是否已经存在
	 * 
	 * @return
	 */
	public boolean ifAddressExist(String addr) {
		for (BlueToothDeviceContext devcie : discoveredDevices) {
			if (addr.equals(devcie.address))
				return true;
		}
		return false;
	}

	public List<BlueToothDeviceContext> getDiscoveredDevices() {
		return discoveredDevices;
	}

	public boolean ifBondExist(String addr) {
		for (BluetoothDevice devcie : bonddevices) {
			if (addr.equals(devcie.getAddress()))
				return true;
		}
		return false;
	}

	/**
	 * 启动蓝牙搜索
	 */
	public void startDiscovery() {
		if (bluetoothAdapter.isEnabled()) {
			if (discoveredDevices != null) {
				discoveredDevices.clear();
			}
			if (bonddevices != null) {
				bonddevices.clear();
			}
			Set<BluetoothDevice> bonddevice = bluetoothAdapter.getBondedDevices();
			if (bonddevice.size() > 0) {
				for (Iterator iterator = bonddevice.iterator(); iterator.hasNext();) {
					bluedevice = (BluetoothDevice) iterator.next();
					bonddevices.add(bluedevice);
				}
			}
			selectBtAddrToInit();
			bluetoothAdapter.startDiscovery();
			baseActivity.showMessage("正在搜索...", MessageTag.TIP);
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						baseActivity.showMessage("蓝牙搜索异常：", MessageTag.ERROR);
					} finally {

						bluetoothAdapter.cancelDiscovery();
						if (isconnect == false) {
							baseActivity.showMessage("停止搜索...", MessageTag.TIP);
							bluetoothAdapter.cancelDiscovery();
						}
					}
				}
			}).start();
		} else {
			baseActivity.showMessage("蓝牙未打开", MessageTag.ERROR);
			Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			baseActivity.startActivityForResult(enabler, REQUEST_ENABLE);
		}

	}

	// 弹出已配对蓝牙对话框,点击链接相应设备
	public void selectBtAddrToInit() {
		dialog = new OptionsDialog(baseActivity, new OnOptionsClickedListener() {

			@Override
			public void onOptionsClicked(View view, int position) {
				bluetoothAdapter.cancelDiscovery();
				deviceToConnect = discoveredDevices.get(position).address;
				deviceName = discoveredDevices.get(position).name;
				isconnect = true;
				new Thread(new Runnable() {
					@Override
					public void run() {
						initController();
					}
				}).start();
			}
		}, discoveredDevices, bonddevices, new OnBondClickedListener() {

			@Override
			public void onBondClicked(View view, int position) {
				bluetoothAdapter.cancelDiscovery();
				deviceToConnect = bonddevices.get(position).getAddress();
				deviceName = bonddevices.get(position).getName();
				isconnect = true;
				new Thread(new Runnable() {
					@Override
					public void run() {
						initController();
					}
				}).start();
			}
		}, new ListButtonClickListener() {
			@Override
			public void onItemButtonClick(int position, List<BluetoothDevice> bonddevices) {
				unpairDevice(bonddevices.get(position));
				dialog.refreshList(bonddevices.get(position));
			}
		}) {

			@Override
			public boolean onKeyDown(int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					keyback();
				}
				return super.onKeyDown(keyCode, event);
			}
		};

		baseActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					dialog.show();
				} catch (BadTokenException e) {
					baseActivity.showMessage("弹出已配对蓝牙对话框异常："+e.getMessage(), MessageTag.ERROR);
				}
			}
		});
	}

	// 初始化蓝夜设备的控制器
	@Override
	public void initController() {
		ME3xDeviceDriver me3xDeviceController = new ME3xDeviceDriver(baseActivity);
		controller = me3xDeviceController.initMe3xDeviceController(ME3X_DRIVER_NAME, new BlueToothV100ConnParams(deviceToConnect,
				new DeviceEventListener<DeviceMenuEvent>() {
					@Override
					public void onEvent(DeviceMenuEvent event, Handler arg1) {
						try {
							String eCode = event.getEcode();
							baseActivity.showMessage("菜单代码：", MessageTag.DATA);
						} catch (Exception ex) {
							baseActivity.showMessage("菜单错误", MessageTag.ERROR);
						}
					}

					@Override
					public Handler getUIHandler() {
						return null;
					}
				}));
		baseActivity.showMessage("控制器已初始化!", MessageTag.TIP);
		baseActivity.btnStateToWaitingConn();
	}

	public BroadcastReceiver getDiscoveryReciever() {
		return discoveryReciever;
	}

	public void keyback() {
		dialog.dismiss();
		bluetoothAdapter.cancelDiscovery();
	}

	public void connectDevice() {
		baseActivity.showMessage("设备连接中...", MessageTag.TIP);
		try {
			controller.connect();
			baseActivity.showMessage("设备连接成功...", MessageTag.TIP);
			
		} catch (Exception e1) {
			e1.printStackTrace();
			baseActivity.showMessage("蓝牙链接异常,请检查设备或重新连接...", MessageTag.ERROR);
		}

	}

	@Override
	public void disconnect() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if (controller != null) {
						controller.disConnect();
						controller = null;
						baseActivity.showMessage("控制器断开成功...", MessageTag.TIP);
						baseActivity.btnStateToWaitingInit();
					}
				} catch (Exception e) {
					Log.e("控制器断开异常", "deleteCSwiper failed!", e);
					baseActivity.showMessage("蓝牙控制器断开异常："+e, MessageTag.ERROR);
				}
			}
		}).start();
	}

	@Override
	public DeviceControllerInterface getController() {
		return controller;
	}

	@Override
	public boolean isControllerAlive() {
		if (controller != null) {
			return true;
		}
		return false;
	}

}
